//
//  HMOriginalView.swift
//  weibo28
//
//  Created by 范英强 on 16/3/25.
//  Copyright © 2016年 范英强. All rights reserved.
//

import UIKit
import SnapKit
class HMOriginalView: UIView {
    
    var originalViewBottomConstraint:Constraint?
    
    var status: HMStatus?{
        didSet{
            // 设置头像
            headImageView.sd_setImageWithURL(NSURL(string: status?.user?.profile_image_url ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
            // 设置昵称
            nameLabel.text = status?.user?.name
            // 会员等级
            mbrankImageView.image = status?.user?.mbrankImage
            // 时间（先这么个默认数据 后续再处理）
            
            // 来自哪里 （先这么个默认数据 后续再处理）
            sourceLabel.text = getSourceStr(status!.source!)

            // 认证
            verifiedImageView.image = status?.user?.verifiedImage
            // 文字内容
            contentLabel.text = status?.text
            
            originalViewBottomConstraint?.uninstall()
            if status?.pic_urls?.count > 0 {
                pictureView.pictureInfo = status?.pic_urls
                pictureView.hidden = false
                self.snp_updateConstraints(closure: { (make) -> Void in
                   self.originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(HMStatusCellMargin).constraint
                })
                
            }else{
                pictureView.hidden = true
                
                self.snp_updateConstraints(closure: { (make) -> Void in
                    self.originalViewBottomConstraint = make.bottom.equalTo(contentLabel).offset(HMStatusCellMargin).constraint
                })
                
                
                
            }
            
            
            
           print(getCreateTime(status!.created_at!))
            let d = getCreateTime(status!.created_at!)!
            
            
            timeLabel.text = showTime(d)
        }
    }
    
    func getCreateTime(time: String) -> NSDate?{
        
        // 实例化  formatter
        let df = NSDateFormatter()
        // 指定格式
        //Sat Mar 19 17:07:20 +0800 2016
        df.dateFormat = "EEE MM dd HH:mm:ss z yyyy"
        // 设置本地化
        df.locale = NSLocale(localeIdentifier: "en_US")
        // 将时间字符串转date
        let date = df.dateFromString(time)
        return date
    }
    
    // 
    func showTime(date: NSDate) -> String{
        // 实例化calendar
        let cl = NSCalendar.currentCalendar()
        // 实例化  formatter
        let df = NSDateFormatter()
        
        let result = cl.components(.Year, fromDate: date, toDate: NSDate(), options: [])
        
        
        // 如果是今年的话 
        if result.year == 0{
            
            /**
            *  如果是今天
                    小于1分钟 ---- 刚刚
                    小于1小时 ---- xx分钟前
                    其他     ---- xx小时前
            */
            if cl.isDateInToday(date){
                
                let s = Int(NSDate().timeIntervalSinceDate(date))
                
                if s < 60{
                    return "刚刚"
                }else if s < 60 * 60{
                    return "\(s / 60)分钟前"
                }else{
                    return "\(s / (60 * 60))小时前"
                }
                
            }else if cl.isDateInYesterday(date){
                /**
                *  如果是昨天的话 ----- 昨天 HH:mm
                */
                df.dateFormat = "昨天 HH:mm"
                
            }else{
                /**
                *  如果是今年  ----- MM-dd HH:mm
                */
                df.dateFormat = "MM-dd HH:mm"
                
            }
            
        }else{
            // 不是今年的
            
            // 格式: yyyy-MM-dd HH:mm
            df.dateFormat = "yyyy-MM-dd HH:mm "
            
        }
        return df.stringFromDate(date)
    }
    
    func getSourceStr(source: String) -> String{
        if source.containsString("\">"){
            let startIndex = source.rangeOfString("\">")!
            let endIndex = source.rangeOfString("</a")!
            
            let str = source.substringWithRange(startIndex.endIndex..<endIndex.startIndex)
            return str
            
        }
        
       
        return ""
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: -  设置视图
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        // 01 添加控件
        addSubview(headImageView)
        addSubview(nameLabel)
        addSubview(mbrankImageView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(verifiedImageView)
        addSubview(contentLabel)
        addSubview(pictureView)
        // 02 添加约束
        headImageView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self).offset(HMStatusCellMargin)
            make.leading.equalTo(self).offset(HMStatusCellMargin)
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headImageView)
            make.leading.equalTo(headImageView.snp_trailing).offset(HMStatusCellMargin)
        }
        
        mbrankImageView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(nameLabel)
            make.leading.equalTo(nameLabel.snp_trailing).offset(HMStatusCellMargin)
        }
        
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(headImageView)
            make.leading.equalTo(nameLabel)
        }
        
        sourceLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(timeLabel)
            make.leading.equalTo(timeLabel.snp_trailing).offset(HMStatusCellMargin)
        }
        
        verifiedImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(headImageView.snp_trailing)
            make.centerY.equalTo(headImageView.snp_bottom)
        }
        
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(headImageView)
            make.top.equalTo(headImageView.snp_bottom).offset(HMStatusCellMargin)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(contentLabel)
            make.top.equalTo(contentLabel.snp_bottom).offset(HMStatusCellMargin)
        }
        
        self.snp_makeConstraints { (make) -> Void in
            self.originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(HMStatusCellMargin).constraint
        }
        
        
    }
    
    // MARK: - 懒加载控件
    // 头像
    private lazy var headImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    // 昵称
    private lazy var nameLabel:UILabel = {
        let lab = UILabel(textColor: UIColor.darkGrayColor(), font: 14)
        lab.text = "名字"
        return lab
    }()
    // 会员等级
    private lazy var mbrankImageView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    //时间
    private lazy var timeLabel: UILabel = {
        let lab = UILabel(textColor: themeColor, font: 10)
        return lab
    }()
    //来自哪里
    private lazy var sourceLabel: UILabel = {
        let lab = UILabel(textColor: UIColor.grayColor(), font: 10)
        return lab
    }()
    
    // 认证
    private lazy var verifiedImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_vgirl"))
    
    // 文字
    private lazy var contentLabel: UILabel = {
        let lab = UILabel(textColor: UIColor.darkGrayColor(), font: 14, maxWidth: SCREENW - 2 * HMStatusCellMargin)
        return lab
    }()
    // 配图
    private lazy var pictureView: HMPictureView = HMPictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    

}
